<?php

require_once("User.php");
require_once("PHPFileStorage.php");

class UserList {
	
	/**
	 * @var array User
	 */
	private $userList;
	/**
	 * @var PHPFileStorage
	 */
	private $userFile;
	/**
	 * @var string
	 */
	private $filePath = "Data/UserListData.php";
	
	public function __construct() {
		$this->userFile = new PHPFileStorage($this->filePath);
		$this->userList = array();
		$this->loadAll();
	}
	
	/**
	 * @var User $user
	 */
	public function loadAll(){
		try{
			$allUsers = $this->userFile->readAll();
			foreach ($allUsers as $user => $value) {
				$user = User::fromString($value);
				$this->userList[$user->getUsername()] = $user;
			}
		}
		catch (\Exception $e) {
			// Create Admin.
			$user = new User("Admin", "Password", false);
			$this->update($user);
			$this->userList[$user->getUsername()] = $user;
		}
	}
	
	/**
	 * @throws  Exception if user provided is not in list
	 * @param  User $fromClient
	 * @return User from list
	 */
	public function findUser(User $fromClient) {
		foreach($this->userList as $user) {
			if ($user->isSame($fromClient) ) {
				return $user;
			}
		}
		throw new \Exception("Could not find user.");
	}
	
	/**
	 * @param User $changedUser
	 */
	public function update(User $changedUser) {
		$this->userFile->changeItem($changedUser->getUsername(), $changedUser->toString());
		$this->userList[$changedUser->getUsername()] = $changedUser;
	}
	

}
